<?php
declare (strict_types = 1);

namespace app\listener;

use think\swoole\Websocket;
use think\swoole\websocket\Room;

class SwRoomLeave
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event,Websocket $ws,Room $room)
    {
          //
        $roomid  = $event['room'];
        $fd      = $ws->getSender();
        $roomfds = $room->getClientList($roomid);
        if(!in_array($fd,$roomfds)){
            $ws->emit('roomleavecallback',"{$fd}不在{$roomid}房间中，无法离开");
            return;
        }

        //离开房间
        $ws->leave($roomid);
        $rooms = $room->getRooms($fd);
        $ws->to($roomfds)->emit('roomleavecallback',"{$fd}已离开{$roomid}房间，当前房间人数为".count($rooms));
    }
}
